var express = require('express');
var superagent = require('superagent');
var router = express.Router();

/* GET home page. */


router.get('/index', function(req, res, next) {
  var isPhone = false;
  var agentID = req.headers['user-agent'].toLowerCase().search(/(micromessenger)/);
  if (agentID > 0) {
    isPhone = true;
  }
  else {
    isPhone = false;
  }

  if (global.IO_OAUTH == false) {
    isPhone = false; //暂时屏蔽授权
  }

  var openid = req.query.openid || 'null';
  var access_token = req.query.access_token || 'null';

  superagent
    .get('https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid + '&lang=zh_CN')
    .end(function(err, res4) {
      if (res4.text.indexOf('errcode') > 0 && isPhone) {
        var state = encodeURIComponent(req.url.split('&openid')[0]);

        console.log(' openid为空--------- ');
        superagent
          .get(global.wechatURL + '/wechat_oauth/getAuthorizeURL?state=' + state + '&finalbase=' + global.browserURL)
          .end(function(err, res3) {
            if (res3 !== undefined && res3.ok) {
              res.redirect(res3.text);
              return;
            }
            else {
              console.error('微信授权错误。');
              logger.error('微信授权错误。');
              res.render('error', {});
            }
          });
      }
      else {
        console.log(' 正常请求---------- ');

              //--------
              var thisUrl = req.url;

              var shareUrl = encodeURIComponent((global.browserURL + thisUrl).split('#')[0]);
              superagent
                .get(global.wechatURL + '/wechat_api/jsconfig?url=' + shareUrl)
                .end(function(err, res2) {
                  if (res2 !== undefined && res2.ok) {
                    var renderData = {};
                    renderData.browserURL = global.browserURL;
                    renderData.wxConfig = res2.body;
                    renderData.userInfo = JSON.parse(res4.text);
                      res.render('index', renderData);

                  }
                  else {
                    console.error('微信分享api错误。');
                    logger.error('微信分享api错误。');
                    res.render('error', {});
                  }
                });
              //--------

      }
    });

});

router.get('/routes', function(req, res, next) {
  var thisUrl = req.url;

  var shareUrl = encodeURIComponent((global.browserURL + thisUrl).split('#')[0]);
  superagent
    .get(global.wechatURL + '/wechat_api/jsconfig?url=' + shareUrl)
    .end(function(err, res2) {
      if (res2 !== undefined && res2.ok) {
        var renderData = {};
        renderData.browserURL = global.browserURL;
        renderData.wxConfig = res2.body;
          res.render('routes', renderData);

      }
      else {
        console.error('微信分享api错误。');
        logger.error('微信分享api错误。');
        res.render('error', {});
      }
    });
});

// 参加活动*******************************************************
router.post('/ajax/join', function(req, res, next) {
  console.log('参加活动');
  superagent
    .post(global.baseURL + '/api/actives/join')
    .send({
      id: req.body.activeId,
    })
    .set('DEVICE', 'weixin')
    .set('USER_ID', req.body.userId)
    .set('TOKEN', req.body.token)
    .end(function(err1, res1) {
      if (res1 !== undefined && res1.ok) {
        res.send(res1.body);
      }
      else {
        console.error('请求数据错误! ');
        logger.error('请求数据错误。');
      }
    });
});

// 判断活动资格*******************************************************
router.post('/ajax/check', function(req, res, next) {
  console.log('判断活动资格');
  superagent
    .post(global.baseURL + '/api/actives/check')
    .send({
      id: req.body.activeId,
    })
    .set('DEVICE', 'weixin')
    .set('USER_ID', req.body.userId)
    .set('TOKEN', req.body.token)
    .end(function(err1, res1) {
      if (res1 !== undefined && res1.ok) {
        res.send(res1.body);
      }
      else {
        console.error('请求数据错误! ');
        logger.error('请求数据错误。');
      }
    });
});


module.exports = router;
